package cn.gailvlun.gll.presentation.emotion.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.util.DensityUtil;



public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
    private int spanCount;
    private int spacing;
    private boolean includeEdge;
    private Context context;
    @ColorInt
    private int color;
    private Paint paint;

    public GridSpacingItemDecoration(int spanCount, float spacing, Context context) {
        this(spanCount, spacing, true, context, R.color.lightGrey);
    }

    public GridSpacingItemDecoration(int spanCount, float spacing, boolean includeEdge, Context context, @ColorRes int colorRes) {
        this.spanCount = spanCount;
        this.spacing = DensityUtil.dp2px(context, spacing);
        this.includeEdge = includeEdge;
        this.context = context;
        this.color = ContextCompat.getColor(context, colorRes);
        paint = new Paint();
        paint.setColor(color);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int column = position % this.spanCount;
        if (this.includeEdge) {
            outRect.left = this.spacing - column * this.spacing / this.spanCount;
            outRect.right = (column + 1) * this.spacing / this.spanCount;
            if (position < this.spanCount) {
                outRect.top = this.spacing;
            }

            outRect.bottom = this.spacing;
        } else {
            outRect.left = column * this.spacing / this.spanCount;
            outRect.right = this.spacing - (column + 1) * this.spacing / this.spanCount;
            if (position < this.spanCount) {
                outRect.top = this.spacing;
            }

            outRect.bottom = this.spacing;
        }

    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {

        super.onDraw(c, parent, state);
        int childCount = parent.getChildCount();
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        int space = DensityUtil.dp2px(parent.getContext(), 8);
        for (int i = 0; i < childCount - 1; i++) {
            View view = parent.getChildAt(i);

            float top = view.getBottom();
            float bottom = view.getBottom() + space;
            c.drawRect(left, top, right, bottom, paint);

        }
    }
}
